/**
 *	url参数拼接
 * @param url
 * @param params
 * @returns
 */
export function urlPlus(url: string, params: StringIndex) {
	Object.keys(params).forEach((item: string, index: number) => {
		url += `${index === 0 ? "?" : "&"}${item}=${params[item]}`;
	});
	return url;
}

/**
 * 获取 url 参数
 * @param url
 * @returns
 */
export function getUrlParams(url = window.location.href) {
	const paramsStr = url.split("?").length > 1 ? url.split("?")[1] : "";
	const params: StringIndex = {};
	if (paramsStr) {
		paramsStr.split("&").forEach(item => {
			const val = item.split("=");
			params[val[0]] = val[1];
		});
	}
	return params;
}

/**
 * 打开新窗口/链接
 * @param url
 * @param flag
 * @returns
 */
export function openWindow(url: string, flag = true) {
	if (flag) {
		window.open(url);
		return;
	}
	window.location.href = url;
}

/**
 * Converts a String or Number type to a percentage or px
 * @param value
 * @param defaultValue
 * @returns
 */
export function nsToPxPct(value: string | number, defaultValue?: number) {
	const defaultData = defaultValue ? `${defaultValue}px` : "100%";
	return typeof value === "string"
		? value.includes("px") || value.includes("%")
			? value
			: isNaN(Number(value))
			? defaultData
			: `${Number(value)}px`
		: typeof value === "number"
		? `${value}px`
		: defaultData;
}

/**
 * use JSON api
 * @param data
 * @returns
 */
export const deepJSON = <T = any>(data: T) => {
	return JSON.parse(JSON.stringify(data)) as T;
};

export function typeOf(value: any) {
	const map: StringIndex = {
		"[object Boolean]": "boolean",
		"[object Number]": "number",
		"[object String]": "string",
		"[object Function]": "function",
		"[object Array]": "array",
		"[object Date]": "date",
		"[object RegExp]": "regExp",
		"[object Undefined]": "undefined",
		"[object Null]": "null",
		"[object Object]": "object",
	};
	return map[Object.prototype.toString.call(value) as string];
}

export function deepCopy(data: any) {
	const t = typeOf(data);
	let o: any;
	if (t === "array") {
		o = [];
	} else if (t === "object") {
		o = {};
	} else {
		return data;
	}
	if (t === "array") {
		for (let i = 0; i < data.length; i++) {
			o.push(deepCopy(data[i]));
		}
	} else if (t === "object") {
		for (const i in data) {
			o[i] = deepCopy(data[i]);
		}
	}
	return o;
}
